#include "smartsortfilterproxymodel.h"
#include <QStringList>
#include <QDebug>
#include "service.h"


SmartSortFilterProxyModel::SmartSortFilterProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
}


void SmartSortFilterProxyModel::setFilter(const QString &str, const QString &fields)
{
    currentFilter = str;

    QStringList list = fields.split(",");
    filterFields.clear();
    foreach(QString element, list)
        filterFields.append(element);

    //qDebug()<<posInFile<<list;

    invalidateFilter();
//    setFilterFixedString(str);
  //  invalidate();

  // qDebug()<<rowCount();
}


bool SmartSortFilterProxyModel::filterAcceptsRow(int sourceRow,
                                                 const QModelIndex &sourceParent) const
{
    if (currentFilter.isEmpty())
        return false;

    bool contain = false;

   // qDebug()<<posInFile<<sourceRow;
    foreach (QString str, filterFields) {
        bool isContain = true;
        if(str.startsWith("=")){
            str = str.mid(1);
            isContain = false;
        }
        QModelIndex index0 = sourceModel()->index(sourceRow, str.toInt(), sourceParent);

        if(isContain)
            contain = sourceModel()->data(index0).toString().contains(currentFilter,Qt::CaseInsensitive);
        else{
            contain = QString::compare(sourceModel()->data(index0).toString(), currentFilter, Qt::CaseInsensitive)==0;
        }

        if(contain) break;
    }
    return contain;
}

QVariant SmartSortFilterProxyModel::getValue(int row, int column)
{
    return data(index(row, column)).toString();
}
